/*
 * Created on Aug 6, 2008
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.scalar.chiptrack.adaptor.ikanos.ams;

import java.io.BufferedInputStream;
import java.net.URL;

import HTTPClient.CookieModule;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.NVPair;

import com.scalar.ScalarException;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.StringUtils;
import Acme.HtmlScanner;

/**
 * @author ravi
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class AMSAdaptor extends JobHandler implements AdaptorConstants
{
    private static final int PORT                       = 80;
    private static final String HOST                    = "asic.austriamicrosystems.com";
    private static final String POST_URI_LOGIN          = "/cgi-sbin/cis/i-Foundry.cgi";

    public static final String FILE_NAME_SHIP_STATUS    = "AMS_SHIP_STATUS";
    public static final String FILE_NAME_WIP_STATUS     = "AMS_WIP_STATUS";
	public static final String ADAPTOR_NAME             = "AMS_FAB";

    private String m_dataOutputDir      = null;
    private Logger m_adaptorLogger      = null;
    private String m_username           = null;
    private String m_password           = null;
    private int    m_adaptor_id     = -1;
    private AMSHtmlObserver m_observer = null;
    private static URL s_dummyUrl = null;
    private boolean isFileNotFound = false;

    public AMSAdaptor() throws Exception
    {
        if ( s_dummyUrl == null )
        {
            try
            {
                s_dummyUrl = new URL( "http://" + HOST );

            }
            catch ( Exception ignore )
            {
                throw ignore;
            }
        }

         try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_AMS, LOCATION_TYPE_FAB );

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_AMS );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( Exception se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading AMS Adaptor Username, Password details from database, Exception: " + se );
            throw new ScalarException( "Exception while loading AMS Adaptor Username, Password details from database" );
        }

        m_observer = new AMSHtmlObserver();
    }

    public static void main( String[] args ) throws Exception
    {
        new AMSAdaptor().execute();
    }

    public void execute() throws Exception
    {
        m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
        //Print the header details
        AdaptorUtils.printHeader(VENDOR_NAME_AMS, CONSTANT_ADAPTOR);

        AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

        HTTPConnection connection = login( HOST , PORT   );

        if ( connection != null )
        {
            BufferedInputStream bfReader = null;
            try
            {
                //For DownLoading WipStatus Report
                HTTPResponse rsp = requestWipStatusReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Wip and Orders Sheet..." );
                        log( "\tDownloading the Wip Status Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_WIP_STATUS , FILE_EXTN_XLS,true );

                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Wip and Orders Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Wip and Orders Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Wip and Orders Sheet" );
                    throw new ScalarException( "Could not create response object of Wip and Orders Sheet" );
                }

                 //For DownLoading Ship Alert Report
                rsp = requestShippingReport( connection );

                if( rsp != null )
                {
                    bfReader = new BufferedInputStream( rsp.getInputStream()  );
                    if( bfReader != null )
                    {
                        System.out.println( "\tDownloading the Ship Alert Sheet..." );
                        log( "\tDownloading the Ship Alert Sheet..." );
                        AdaptorUtils.saveAsBinaryFile( bfReader, m_dataOutputDir, FILE_NAME_SHIP_STATUS ,FILE_EXTN_XLS,true );
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_STATUS, FILE_EXTN_XLS, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Ship Alert Sheet from Buffer Reader" );
                        throw new ScalarException( "Could not save Ship Alert Sheet from Buffer Reader" );
                    }
                }
                else
                {
                    if ( isFileNotFound )
                    {
                        System.out.println("No such file or directory: 00005_010107_Ikanos/Ship_alert" + m_observer.getMaxYearNo() +"/Ship Info_"+ m_observer.getMaxFileNo()+ "_" + m_observer.getMaxYearNo()+ ".xls" );
                    }
                    else
                    {
                        log( "Could not create response object of Ship Alert Sheet" );
                        throw new ScalarException( "Could not create response object of Ship Alert Sheet" );
                    }
                }

                // Logging out from AMS WEB SITE
                //logout( connection );
                 bfReader = null;
            }
            finally
            {
                 if ( bfReader != null )
                 {
                     bfReader.close();
                     bfReader = null;
                 }
            }

        }
        else
        {
            log( "Could not able to get the Connection to web site" );
            throw new ScalarException( "Could not able to get the Connection to web site" );
        }
    }

    /**
     *
     * @param host
     * @param port
     * @return
     * @throws Exception
     */

    private HTTPConnection login( String host, int port ) throws Exception
    {
        byte[] data         = new byte[1024];

        HTTPConnection conn = new HTTPConnection(host, port );
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

       NVPair defaultHeaders[] = new NVPair[ 6 ];
        defaultHeaders[ 0 ] = new NVPair( "Accept", "**/*//*" );
        defaultHeaders[ 1 ] = new NVPair( "Accept-Language", "en-us" );
        defaultHeaders[ 2 ] = new NVPair( "Content-Type", "application/x-www-form-urlencoded" );
        defaultHeaders[ 3 ] = new NVPair( "Proxy-Connection", "Keep-Alive" );
        defaultHeaders[ 4 ] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; SOL/4.0)" );
        defaultHeaders[ 5 ] = new NVPair( "Host", host );


        conn.setDefaultHeaders( defaultHeaders );

        HTTPResponse rsp = conn.Get( "/i-foundry/" );

        System.out.print( "Trying to Logging in......" );
        log( "Trying to Logging in......" );

        conn.addBasicAuthorization("non-public area", m_username, m_password );

        rsp  = conn.Get( POST_URI_LOGIN );

        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
        	log( new String( data ) );
        }*/

        rsp = conn.Get("/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos");

       log( "Response from Server: " + rsp.getStatusCode() + " " + rsp.getReasonLine() );

        if ( rsp.getStatusCode() >= 400 )
        {
            System.out.println( "Login failed.. response from server: " + rsp.getStatusCode() );
            log( "Login failed.. response from server: " + rsp.getStatusCode() );
            conn = null;
        }

        log( "Done." );
        return conn;
    }

    private HTTPResponse requestWipStatusReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse   rsp  = null;

        System.out.println( "\nSubmitting the request for Wip and Orders Info......" );
        log( "Submitting the request for  Wip and Orders Info......" );

        rsp = conn.Get("/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos/wip_and_orders.html" ) ;

        rsp = conn.Get("/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos/WIP_and_ORDERS/00000_010107_WIP.xls");
        /*while ( rsp.getInputStream().read( data ) != -1 )
        {
            log( new String( data ) );
        }*/

        return rsp;
    }


    private HTTPResponse requestShippingReport( HTTPConnection conn) throws Exception
    {
        byte[] data         = new byte[1024];
        HTTPResponse rsp = null;

        System.out.println( "Submitting the request for Shipping Info......" );
        log( "Submitting the request for Shipping Info......" );

        rsp = conn.Get( "/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos/shipping_info.html" );
        HtmlScanner htmlScanner1 = new HtmlScanner( rsp.getInputStream(), s_dummyUrl, m_observer );
        while ( htmlScanner1.read( data ) != -1 )
        {
            //System.out.println (new String(data));
        }

        rsp = conn.Get( "/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos/Ship_alert_" + m_observer.getMaxYearNo() );

        HtmlScanner htmlScanner = new HtmlScanner( rsp.getInputStream(), s_dummyUrl, m_observer );
        while ( htmlScanner.read( data ) != -1 )
        {
            //System.out.println (new String(data));
        }

        if ( m_observer.getMaxFileNo() > 0 )
        {
            rsp = conn.Get("/cgi-sbin/cis/i-Foundry.cgi?00005_010107_Ikanos/Ship_alert_"+m_observer.getMaxYearNo() +"/Ship Info_"+ m_observer.getMaxFileNo()+ "_" + m_observer.getMaxYearNo()+ ".xls");
        }
        else
        {
            rsp = null;
            isFileNotFound = true;
        }
        return rsp;
    }


    private void log( String message )
    {
        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}
